package com.anxin.registerManagement.util;

/**
 * @author 叶前呈
 * @date 2022/1/21 10:52
 */

import cn.hutool.core.util.ReflectUtil;
import java.util.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;

/**
 * 通用工具类
 */
public class CommonUtil {
    private static Logger logger = LoggerFactory.getLogger(CommonUtil.class);

    /**
     * 实体类属性去掉空格
     *
     * @param model
     */
    public static void trimBean(Object model) {
        logger.info("去除实体类属性空格");
        Class<?> clazz = model.getClass();
        Field[] fields = ReflectUtil.getFields(clazz);
        for (Field field : fields) {
            if ("class java.lang.String".equals(field.getGenericType().toString())) {
                Object value = ReflectUtil.getFieldValue(model, field);
                if (value != null) {
                    value = String.valueOf(value).trim();
                    field.setAccessible(true);
                    try {
                        field.set(model, value);
                    } catch (IllegalAccessException e) {
                        logger.info("实体类去除空格异常");
                    }
                }
            }
        }
    }

    /**
     * 读取json文件
     */
    public static String readJsonFile(String fileName) {
        String path = Objects.requireNonNull(CommonUtil.class.getClassLoader().getResource(fileName)).getPath();
        String jsonStr = "";
        try {
            File jsonFile = new File(path);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), StandardCharsets.UTF_8);
            int ch = 0;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成随机数
     *
     * @param sum 随机数个数
     * @return
     */
    public static String verificationCode(int sum) {
        if (sum <= 0) {
            return null;
        } else {
            StringBuilder randomNumber = new StringBuilder();
            String number = "1234567890AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwSsYyZz";
            Random random = new Random();
            random.nextInt();
            for (int i = 0; i < sum; i++) {
                randomNumber.append(number.charAt(random.nextInt(number.length())));
            }
            return randomNumber.toString();
        }
    }

}
